package service

import (
	"os/exec"
	"server-admin-api/dto"
	"server-admin-api/message"
	"server-admin-api/models"
	"server-admin-api/views"
	"strconv"
)

type CustomizeService struct {
	customizeDto *dto.CustomizeDto
}

func NewCustomizeService() *CustomizeService {
	return &CustomizeService{
		customizeDto: dto.NewCustomizeDto(),
	}
}

func (c *CustomizeService) PageData(params views.CustomizePageVo) (message.DataPage, error) {
	count, err := c.customizeDto.Count(params)
	if err != nil {
		return message.ErrorDataPage(), err
	}
	finds, err := c.customizeDto.Finds(params)
	if err != nil {
		return message.ErrorDataPage(), err
	}
	return message.NewDataPage(finds, count, params.Page, params.Size), nil
}


func (c *CustomizeService) ScriptRun(id string) error {
	pk, _ := strconv.Atoi(id)
	customize, err := c.customizeDto.FindOne(pk)
	if err != nil {
		return err
	}
	command := exec.Command("bash", "-c", customize.Script)
	err = command.Run()
	return err
}

// CreateModel 创建服务
func (c *CustomizeService) CreateModel(id int, param views.CustomizeCreate) error {
	var data models.Customize
	if id == 0 {
		data = models.Customize{}.NewBuild(param)
		return c.customizeDto.Insert(data)
	} else {
		return c.customizeDto.Update(id, param)
	}
}


func (c *CustomizeService) DeleteById(id int) bool {
	if err := c.customizeDto.DeleteOne(id); err != nil {
		return false
	}
	return true
}
